package v1

import (
	"bytes"
	"encoding/json"
	"flag"
	"gin-demo/pkg/setting"
	"gin-demo/pkg/util"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

// 对接 chatgpt3 的api
var (
	msgFlag string
)

// 初始化
func init() {
	flag.StringVar(&msgFlag, "msg", "", "文本消息")
}

// 请求
type Chat3Request struct {
	Model     string `json:"model"`
	MaxTokens int    `json:"max_tokens"`
	Prompt    string `json:"prompt"`
}

// 响应
type Chat3Response struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Text         string      `json:"text"`
		Index        int         `json:"index"`
		Logprobs     interface{} `json:"logprobs"`
		FinishReason string      `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

func ChatGPT3Request(c *gin.Context) {
	// 打印配置
	log.Println("chatgpt3的配置：", setting.ChatGPT3Conf)

	question := c.Query("prompt")

	returnObj := util.NewResponseSuccess()

	if question == "" {
		returnObj.Code = 422
		returnObj.Msg = "prompt参数不能为空"
		util.ResponseSuccess(c, returnObj)
		return
	}

	if setting.ChatGPT3Conf.API_KEY == "" {
		returnObj.Code = 422
		returnObj.Msg = "apikey不能为空"
		util.ResponseSuccess(c, returnObj)
		return
	}

	chatReq := Chat3Request{
		Model:     "text-davinci-003",
		MaxTokens: 100,
		Prompt:    question,
	}

	// 请求体转成json
	reqJson, err := json.Marshal(&chatReq)
	if err != nil {
		returnObj.Code = 422
		returnObj.Msg = "请求体转成json失败：" + err.Error()
		util.ResponseSuccess(c, returnObj)
		return
	}

	// 创建一个http
	req, err := http.NewRequest("POST", setting.ChatGPT3Conf.END_POINT, bytes.NewReader(reqJson))
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Bearer "+setting.ChatGPT3Conf.API_KEY)
	req.Header.Add("User-Agent", "chatGPT/1 CFNetwork/1402.0.8 Darwin/22.2.0")
	req.Header.Add("Accept-encoding", "gzip, deflate, br")
	req.Header.Add("Accept-language", "zh-CN,zh-Hans;q=0.9")
	// 代理地址
	proxyAddress, _ := url.Parse(setting.ChatGPT3Conf.PROXY)
	client := &http.Client{
		Timeout: 300 * time.Second,
		Transport: &http.Transport{
			Proxy: http.ProxyURL(proxyAddress),
		},
	}
	resp, err2 := client.Do(req)
	if err2 != nil {
		returnObj.Code = 422
		returnObj.Msg = "client.Do失败：" + err2.Error()
		util.ResponseSuccess(c, returnObj)
		return
	}

	readRet, err3 := ioutil.ReadAll(resp.Body)
	if err3 != nil {
		returnObj.Code = 422
		returnObj.Msg = "ioutil.ReadAll失败：" + err3.Error()
		util.ResponseSuccess(c, returnObj)
		return
	}
	defer resp.Body.Close()

	chatResp := &Chat3Response{}
	err = json.Unmarshal(readRet, &chatResp)
	if err != nil {
		returnObj.Code = 422
		returnObj.Msg = "json.Unmarshal失败：" + err2.Error()
		util.ResponseSuccess(c, returnObj)
		return
	}

	// 数据返回
	returnObj.Data = chatResp
	util.ResponseSuccess(c, returnObj)
}
